﻿using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using OA.Common;
using OA.Models;
using OA.Models.Enums;
using OA.Models.ViewModels;
using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace OA.Controllers
{
    public class AccountsController : BaseController
    {
        /// <summary>
        ///  登录页
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
        }

        /// <summary>
        ///  登录
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(LoginViewModel account)
        {
            try
            {
                //if (!CaptchaHelper.Check(account.Captcha))
                //{
                //    throw new Exception("验证码错误!");
                //}

                var user = Context.Accounts.SingleOrDefault(d => d.Id.Equals(account.Id));

                // 判断是否有该用户名
                if (user == null)
                {
                    throw new Exception("工号不存在!");
                }

                // 判断密码是否正确
                var _md5 = SecurityHelper.MD5Encrypt(account.Password);
                if (!user.Password.Equals(_md5))
                {
                    throw new Exception("密码错误!");
                }

                // 判断账户目前状态是否可用
                if (user.AccountState != AccountState.可用)
                {
                    throw new Exception("账户目前不可用!");
                }

                // 消除图形码 Session
                CaptchaHelper.ClearSession();
                // 记录登录状态信息
                // Session["userId"] = _account.Id;

                FormsAuthentication.SignOut();

                CurrentUserCookie serializeModel = new CurrentUserCookie
                {
                    CurrentUser = new UserInfo
                    {
                        UserId = user.Id,
                        Name = user.Name,
                        Department = user.Department.Name,
                        Post = user.Post.Name
                    }
                };

                System.Web.HttpContext.Current.User = serializeModel;

                string userData = Newtonsoft.Json.JsonConvert.SerializeObject(serializeModel);
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                        1,
                        user.Id.ToString(),
                        DateTime.Now,
                        DateTime.Now.AddYears(5),
                        true,
                        userData);
                string encTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                cookie.HttpOnly = true;
                cookie.Expires = DateTime.Now.AddMonths(1);
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);

                return RedirectToAction("Index", "Home");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View();
            }
        }

        /// <summary>
        ///  注销
        /// </summary>
        /// <returns></returns>
        public ActionResult LogOut()
        {
            // 移除所有系统相关 Session
            // Session.Clear();
            // 返回到登录界面
            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "Accounts");
        }

        /// <summary>
        ///  注册页面
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        /// <summary>
        ///  注册
        /// </summary>
        /// <param name="entity">账户</param>
        /// <returns></returns>
        [AllowAnonymous]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(RegisterViewModel register)
        {
            //var _h = Context.Accounts.Any(d => d.Username.Equals(register.Id));

            //// 判断是否已有重复的用户名
            //if (_h)
            //{
            //    ModelState.AddModelError("", "该用户名已经存在");
            //    return View();
            //}
            //if (!ModelState.IsValid)
            //{
            //    return View();
            //}

            //var entity = Context.Accounts.Create();

            //entity.Username = register.Id;
            //entity.Password = register.Password;
            //entity.Name = register.Name;
            //entity.Gender = register.Gender;
            //entity.Birthday = register.Birthday;
            //entity.Email = register.Email;
            //entity.Phone = register.Phone;
            //entity.PostId = register.PostId;
            //entity.DepartmentId = register.DepartmentId;
            
            //entity.Photo = "";
            //entity.Createdate = DateTime.Now;
            //entity.AccountState = 0;
            //entity.State = 0;

            try
            {
                //Context.Accounts.Add(entity);
                //Context.SaveChanges();
                //// 清楚图形验证码
                //CaptchaHelper.ClearSession();
                // 注册成功后返回登录界面
                // 等待管理员审核
                return RedirectToAction("Login", "Accounts");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View();
            }
        }

        #region 管理员

        /// <summary>
        ///  账户管理页
        /// </summary>
        /// <returns></returns>
        public ViewResult Index()
        {
            return View();
        }

        /// <summary>
        ///  读取账户集
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Read([DataSourceRequest] DataSourceRequest request)
        {
            var query = Context.Accounts;

            return Json(query.ToDataSourceResult(request));
        }

        /// <summary>
        ///  账户编辑页
        /// </summary>
        /// <param name="Id">工号</param>
        /// <returns></returns>
        public PartialViewResult Update(string Id)
        {
            var viewModel = new AccountViewModel();

            if (viewModel == null)
            {
                // 新增
                viewModel.Id = "";
                viewModel.IsEdit = false;
                viewModel.IsAdmin = true;
            }
            else
            {
                // 编辑
                var user = Context.Accounts.Find(Id);

                if (user != null)
                {
                    viewModel.Id = Id;
                    viewModel.IsEdit = true;
                    viewModel.IsAdmin = true;

                    viewModel.Password = user.Password;
                    viewModel.Photo = user.Photo;
                    viewModel.Name = user.Name;
                    viewModel.Gender = user.Gender;
                    viewModel.Birthday = user.Birthday;
                    viewModel.Email = user.Email;
                    viewModel.Phone = user.Phone;
                    viewModel.PostId = user.PostId;
                    viewModel.DepartmentId = user.DepartmentId;
                    viewModel.State = user.State;
                }
            }

            return PartialView(viewModel);
        }

        /// <summary>
        ///  新建账户
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Update(AccountViewModel viewModel)
        {
            var user = Context.Accounts.Find(viewModel.Id);
            var isNew = user == null;

            if (isNew)
            {
                if (Context.Accounts.Any(d => d.Id.Equals(viewModel.Id)))
                {
                    return Json(Failed("该工号已经存在!"));
                }

                user = Context.Accounts.Create();

                user.Id = viewModel.Id;
                user.Password = SecurityHelper.MD5Encrypt(viewModel.Password);
                user.Photo = viewModel.Photo;
                user.Name = viewModel.Name;
                user.Gender = viewModel.Gender;
                user.Birthday = viewModel.Birthday;
                user.Email = viewModel.Email;
                user.Phone = viewModel.Phone;
                user.PostId = viewModel.PostId;
                user.DepartmentId = viewModel.DepartmentId;

                user.State = 0;
                user.AccountState = AccountState.可用;
                user.Createdate = DateTime.Now;

                Context.Accounts.Add(user);
            }
            else
            {
                if (viewModel.IsAdmin)
                {
                    // 管理员编辑账户
                    // 姓名, 性别, 头像, 生日, 邮箱, 手机, 岗位, 部门, 在职状态

                    user.Name = viewModel.Name;
                    user.Photo = viewModel.Photo;
                    user.Gender = viewModel.Gender;
                    user.Birthday = viewModel.Birthday;
                    user.Email = viewModel.Email;
                    user.Phone = viewModel.Phone;
                    user.PostId = viewModel.PostId;
                    user.DepartmentId = viewModel.DepartmentId;

                    user.State = viewModel.State;
                }
                else
                {
                    // 用户编辑自己账户
                    // 姓名, 性别, 头像, 生日, 邮箱, 手机
                    user.Name = viewModel.Name;
                    user.Gender = viewModel.Gender;
                    user.Photo = viewModel.Photo;
                    user.Birthday = viewModel.Birthday;
                    user.Email = viewModel.Email;
                    user.Phone = viewModel.Phone;
                }
            }

            try
            {
                Context.SaveChanges();
                return Json(Success(isNew ? "添加成功!" : "更新成功!"));
            }
            catch (Exception ex)
            {
                return Json(Failed("操作失败" + ex.Message));
            }
        }

        /// <summary>
        ///  删除账户
        ///  只能删除状态为 "申请中" 的账户
        /// </summary>
        /// <param name="Id">要删除的账户Id</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete(string Id)
        {
            var user = Context.Accounts.Find(Id);

            if (user == null)
            {
                return Json(Failed("账号获取失败!"));
            }

            if (user.AccountState != 0)
            {
                return Json(Failed("无法删除账户, 请确定账户状态是否为<申请中>!"));
            }

            try
            {
                Context.Accounts.Remove(user);
                Context.SaveChanges();
                return Json(Success("删除成功!"));
            }
            catch (Exception ex)
            {
                return Json(Failed("操作错误!" + ex.Message));
            }
        }

        /// <summary>
        ///  锁定或解锁账户
        /// </summary>
        /// <returns></returns>
        public JsonResult LockOrUnlockAccount(string Id)
        {
            var _a = Context.Accounts.Find(Id);

            if (_a == null)
            {
                return Json(Failed("账户信息错误!"));
            }

            // 如果账户处于<申请中>或者<冻结中>, 则另账户切换到<可用>状态
            // 如果账户处于<可用中>, 则另账户切换到<冻结中>状态
            _a.AccountState = _a.AccountState != AccountState.可用 ? AccountState.可用 : AccountState.锁定;

            try
            {
                Context.SaveChanges();
                return Json(Success(_a.AccountState == AccountState.可用 ? "解锁成功!" : "锁定成功!"));
            }
            catch (Exception ex)
            {
                return Json(Failed(ex.Message));
            }
        }

        /// <summary>
        ///  重置账户密码
        /// </summary>
        /// <param name="Id">账户Id</param>
        /// <returns></returns>
        public JsonResult ResetPassword(string Id)
        {
            var _a = Context.Accounts.Find(Id);

            if (_a == null)
            {
                return Json(Failed("账户信息错误!"));
            }

            _a.Password = SecurityHelper.MD5Encrypt("123456");

            try
            {
                Context.SaveChanges();
                return Json(Success("密码重置成功!"));
            }
            catch (Exception ex)
            {
                return Json(Failed("密码重置失败:" + ex.Message));
            }
        }

        #endregion

    }
}
